<template>
  <div style="height: 100%;background-color:white ;">
    <PreviewDialog ref="preview"
                   :calculatorSore="calculatorSore"
                   :describeContent="describeContent"
                   :fields="fields"
                   :medicalCalculatorData="medicalCalculatorData"
                   :type="cntFormulaType"/>
    <el-row :gutter="24">
      <el-col :span="10">
        <el-button :style="{ display: checkAllEnable }" @click="releaseSelection()" size="small" type="success">公式发布
        </el-button>
        <el-button :style="{ display: checkAllEnable }" @click="releaseAll()" size="small" type="success">一键发布
        </el-button>
        <el-button :style="{ display: reviseEnable }" @click="multiEdit('multi')" plain size="small" type="success">批量修订
        </el-button>
        <el-button :style="{ display: reviseEnable }" @click="multiEdit('all')" plain size="small" type="success">一键修订
        </el-button>
        <el-button :style="{ display: exportEnable }" @click="multipleExportH5" size="small" type="success">批量导出
        </el-button>
        <el-button :style="{ display: exportEnable }" size="small" type="success" @click="allExportH5('')">一键导出
        </el-button>
        <el-button :style="{ display: checkAllEnable }" plain size="small" type="success" @click="option()">设置
        </el-button>
        <el-button :style="{ display: exportEnable }" plain size="small" type="info" @click="recycleSite">回收站
        </el-button>
        <div style="display: inline-block">
          <div style="display: inline-block"><span></span></div>
        </div>
      </el-col>
      <el-col :span="4">
        <el-radio-group @change="valueChange()" size="small" v-model="radioStatus">
          <el-radio-button v-if="showStatus!='true'" label="unpublished">未发布</el-radio-button>
          <el-radio-button v-if="showStatus!='true'" label="published">已发布</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="10" style="right: auto">
        <CalculatorSearch @confirm="refreshTableData" v-model="radioStatus"></CalculatorSearch>
      </el-col>
    </el-row>
    <el-row>
      <div>
        <el-table :data="TableData" :height="tableHeight" border
                  highlight-current-row stripe @selection-change="handleSelectionChange"
                  style="width: 100%;margin-top: 10px">
          <el-table-column
            type="selection"
            v-model="multipleSelection"
            width="40" align="center">
          </el-table-column>
          <el-table-column key='formulaNameCol' label="公式名称" min-width="200" prop="formulaName" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-html="scope.row.formulaName"></span>
            </template>
          </el-table-column>
          <el-table-column key='versionCol' label="版本号" prop="version" width="100"></el-table-column>
          <el-table-column key='formulaTypeCol' label="公式类型" prop="formulaType" width="100">
            <template slot-scope="scope">
              <span v-if="1 === scope.row.formulaType ">计算型</span>
              <span v-if="2 === scope.row.formulaType ">评分型</span>
              <span v-if="3 === scope.row.formulaType ">描述型</span>
            </template>
          </el-table-column>
          <el-table-column :key=index :label="item.name" v-for="(item,index) in tableInnerData[0]">
            <template slot-scope="scope">
              <span v-for="(item2,index2) in scope.row.medicalCalculatorFieldList"
                    v-if="index2 == index"> {{ item2.property }} </span>
            </template>
          </el-table-column>
          <el-table-column key='editorCol' label="编辑人" prop="editor" width="100">
            <template slot-scope="scope">
              <span v-text="UTIL.getNameByUserName(scope.row.editor)"></span>
            </template>
          </el-table-column>
          <el-table-column key='auditorCol' label="审核人" prop="auditor" width="250">
            <template slot-scope="scope">
              <span v-html="scope.row.auditorList.map(UTIL.getNameByUserName).join()"></span>
            </template>
          </el-table-column>
          <el-table-column v-if="this.radioStatus==='published'" label="是否修订" min-width="100" prop="isRevised"
                           show-overflow-tooltip width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.isRevised==1">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column key='propertyCol' label="关联平台" prop="property" width="150"></el-table-column>
          <el-table-column key='updatedTimeCol' :formatter="dateFormat" label="更新时间" min-width="160"
                           prop="updatedTime"></el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
               <span><el-link :style="{ display:exportEnable }" @click.prevent="exportH5(scope.row.id)"
                              type="primary">导出</el-link></span>
              <span><el-link :style="{ display:releaseEnable }" @click.prevent="release(scope.row.id)"
                             type="primary">发布</el-link></span>
              <span><el-link @click.prevent="showLog(scope.row.id)" type="primary">日志</el-link></span>
              <span><el-link @click.prevent="showPreviewDialog(scope.row.id)" type="primary">详情</el-link></span>
              <span><el-link :style="{ display: editEnable }" @click.prevent="revise(scope.row)"
                             type="primary">修订</el-link></span>
              <span><el-link :style="{ display: editEnable }" @click.prevent="correct(scope.row.id)"
                             type="primary">勘误</el-link></span>
              <span><el-link :style="{ display:releaseEnable }" type="primary"
                             @click.prevent="reject(scope.row.id)">驳回</el-link></span>
              <span><el-link :style="{display: editEnable}" type="danger"
                             @click.prevent="del(scope.row.id)">删除</el-link></span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-row>
      <div style="margin-top: 10px">
        <el-pagination :page-size="pageSize"
                       :total="totalNum"
                       :page-sizes="[5, 10, 15, 20, 50, 100]"
                       @current-change="handleCurrentChange"
                       @size-change="handleSizeChange"
                       background
                       layout="total, sizes, prev, pager, next, jumper"
                       style="text-align: right;"
                       v-if="multiplePages"></el-pagination>
      </div>
    </el-row>

    <el-dialog :visible.sync="selectTaskDialogVisible" title="新建子任务" width="500px">
      <el-row>
        <el-col :span="6">
          <span class="label">选择任务<em style="color: red">*</em></span>
        </el-col>
        <el-col :span="18">
          <el-select filterable v-model="selectedTaskId" style="width: 100%"
                     placeholder="请选择">
            <el-option
              v-for="(item,index) in taskList"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">备注</span>
        </el-col>
        <el-col :span="18">
          <el-input v-model.trim="taskItemRemark"/>
        </el-col>
      </el-row>
      <span class="dialog-footer" slot="footer">
        <el-button @click="closeSelectTaskDialog">取 消</el-button>
        <el-button @click="insertTaskItem" type="primary">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import CalculatorSearch from "../../components/calculator/CalculatorSearch";
import moment from "moment";
import PreviewDialog from "./exportModel/PreviewDialog";

export default {
  name: "TempAndReleaseTable",
  components: {
    CalculatorSearch,
    PreviewDialog
  },
  props: ['showStatus'],
  data() {
    return {
      previewDialogVisible: false,
      medicalCalculatorData: [],
      calculatorSore: [],
      describeContent: '',
      fields: [],
      cntFormulaType: 1,

      TableData: [],
      multiplePages: true,
      noData: true,
      totalNum: 0,
      currentPage: 0, // 第几页
      pageSize: 10, // 每页显示的数据个数
      radioStatus: '',
      multipleSelection: [],
      tableHeight: '',
      updateTime: '',
      type: '',
      version: '',
      editor: '',
      auditor: '',
      name: '',
      subject: '',
      platform: '',
      editEnable: 'none',
      checkAllEnable: '',
      releaseEnable: '',
      optionEnable: '',
      reviseEnable: 'none',
      exportEnable: 'none',
      tableInnerData: [],
      exportTableData: [],
      selectedCalculator: {},
      taskList: [],
      selectTaskDialogVisible: false,
      selectedTaskId: '',
      taskItemRemark: '',
      reviseType: ''
    }
  },
  methods: {
    recycleSite() {
      this.$router.push({
          path: '/calculatorRecycle',
        }
      )
    },
    del(id) {
      this.axios.get('/pmph/action/task/selectTaskItemInProcessByKnowledgeId', {
        params: {
          knowledgeId: id,
        }
      }).then((response) => {
        if (response.data.length > 0) {
          this.$message.warning("当前知识正在修订中, 请先删除修订中的知识");
        } else {
          this.$confirm('是否删除？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteCalc(id)
          })
        }
      })
    },
    deleteCalc(id) {
      this.axios.get('/pmph/action/medicalCalculator/deleteReleaseCalcById', {
        params: {
          id: id,
          status: "published"
        }
      }).then((response) => {
        this.getTableData()
        this.$emit("released")
      })
    },
    insertTaskItem() {
      if (!this.selectedTaskId) {
        this.$message.warning("请选择挂载任务")
        return
      }
      // 单条数据修订;
      if (this.reviseType === 'single') {
        let param = new URLSearchParams();
        param.append("taskItem", JSON.stringify({
          taskId: this.selectedTaskId,
          name: this.selectedCalculator.formulaName,
          knowledgeId: this.selectedCalculator.id,
          type: CONST.TASK_ITEM.TYPE_EDIT,
          remark: this.taskItemRemark,
        }))
        this.axios.post('/pmph/action/task/saveTaskItem', param)
          .then(() => {
            this.closeSelectTaskDialog()
          })
      }
      // 一键修订;
      else {
        let param = new URLSearchParams();
        param.append("reviseType", this.reviseType)
        param.append("selectedKnowledgeIds", JSON.stringify(this.multipleSelection.map(item => item.id)))
        param.append("taskId", this.selectedTaskId)
        param.append("remark", this.taskItemRemark)
        param.append('searchParams', JSON.stringify({
          totalNum: this.totalNum,
          updateTime: this.updateTime.toString(),
          type: this.type,
          version: this.version,
          editor: this.editor,
          auditor: this.auditor,
          name: this.name,
          subject: JSON.stringify(this.subject),
          platform: JSON.stringify(this.platform),
          isRevised: this.isRevised
        }));
        this.axios.post('/pmph/action/medicalCalculator/multiInsertTaskItem', param)
          .then(() => {
            setTimeout(this.getTableData, 3000);
            this.closeSelectTaskDialog()
          })
      }
    },
    closeSelectTaskDialog() {
      this.selectTaskDialogVisible = false
      this.taskList = []
      this.taskItemRemark = ''
    },
    multipleExportH5() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请选中需要导出的计算器")
        return
      }
      // 选中的id集合;
      let ids = this.multipleSelection.map(item => item.id).join(",");
      this.allExportH5(ids);
    },
    exportH5(id) {
      this.allExportH5(id);
    },
    allExportH5: function (ids) {
      this.axios.get('/pmph/action/medicalCalculator/exportH5', {
        params: {
          updateTime: this.updateTime.toString(),
          type: this.type,
          version: this.version,
          editor: this.editor,
          auditor: this.auditor,
          name: this.name,
          platform: JSON.stringify(this.platform),
          status: this.radioStatus,
          ids: ids
        },
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/zip'
        }
      }).then((response) => {
        this.downloadFile(response.data);
      })
    },
    downloadFile(data) {
      // 文件导出
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data], {type: "application/zip"}));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', 'export.zip');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放blob对
    },
    //复选框选中事件
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    refreshTableData(nv, totalNum, updateTime, type, version, editor, auditor, name, subject, platform, isRevised) {
      this.TableData = nv
      this.totalNum = totalNum
      this.updateTime = updateTime
      this.type = type
      this.version = version
      this.editor = editor
      this.auditor = auditor
      this.name = name
      this.subject = subject
      this.platform = platform
      this.isRevised = isRevised
    },
    handleCurrentChange: function (val) {
      this.currentPage = val - 1;
      this.getTableData();
    },
    valueChange: function () {
      if (this.radioStatus === 'unpublished') {
        this.editEnable = 'none'
        this.checkAllEnable = ''
        this.releaseEnable = ''
        this.reviseEnable = 'none'
        this.exportEnable = 'none'
      } else {
        this.editEnable = ''
        this.checkAllEnable = 'none'
        this.releaseEnable = 'none',
          this.reviseEnable = ''
        this.exportEnable = ''
      }
      this.getTableData();
    },
    correct: function (id) {
      this.$router.push({
          path: '/formula/editor',
          query: {id: id, auditStatus: 'released', enableCreate: '1'}
        }
      )
    },
    revise: async function (calculator) {
      this.reviseType = 'single'
      this.selectedCalculator = calculator
      let checkFlag = false
      // 查询本知识是否已和正在进行中的子任务关联
      await this.axios.get('/pmph/action/task/selectTaskItemInProcessByKnowledgeId', {
        params: {
          knowledgeId: calculator.id,
        }
      }).then((response) => {
        if (response.data.length > 0) {
          this.$message.warning("当前计算器正在修订中, 请勿重复修订")
        } else {
          checkFlag = true
        }
      })
      if (checkFlag) {
        // 查询当前知识库关联正在进行中的任务, 供用户选择
        this.axios.get('/pmph/action/task/selectTaskInProcessByKnowledgeLibId', {
          params: {
            knowledgeLibId: CONST.KNOWLEDGE_LIB.CALCULATOR_LIB_ID,
          }
        }).then((response) => {
          if (response.data.length > 0) {
            this.taskList = response.data
            this.selectTaskDialogVisible = true
          } else {
            this.$message.warning("计算器没有正在进行中的任务, 请先新建任务!")
          }
        })
      }
    },
    option: function () {
      this.$router.push("/calculatorOption")
    },
    multiEdit: function (reviseType) {
      this.reviseType = reviseType
      if (reviseType === 'multi' && this.multipleSelection.length === 0) {
        this.$message.warning("请选择修订的计算器!")
        return
      }
      // 查询当前知识库关联正在进行中的任务, 供用户选择
      this.axios.get('/pmph/action/task/selectTaskInProcessByKnowledgeLibId', {
        params: {
          knowledgeLibId: CONST.KNOWLEDGE_LIB.CALCULATOR_LIB_ID,
        }
      }).then((response) => {
        if (response.data.length > 0) {
          this.taskList = response.data
          this.selectTaskDialogVisible = true
        } else {
          this.$message.warning("计算器没有正在进行中的任务, 请先新建任务!")
        }
      })
    },
    showLog: function (id) {
      this.$router.push({
          path: '/calculatorLog',
          query: {id: id}
        }
      )
    },
    showPreviewDialog: function (id) {
      let url = ''
      if (this.radioStatus == 'unpublished') {
        url = '/pmph/action/medicalCalculator/selectDataById'
      } else {
        url = '/pmph/action/medicalCalculator/selectReleasedCalculatorById'
      }
      let that = this
      this.axios.get(url, {
        params: {
          id: id,
        }
      }).then((response) => {
        that.medicalCalculatorData = response.data.medicalCalculatorData
        that.calculatorSore = response.data.calculatorSore
        that.describeContent = response.data.describeContent
        if (!this.describeContent) {
          this.describeContent = '无'
        }
        that.fields = response.data.fields
        for (let i = 0; i < that.fields.length; i++) {
          if (that.fields[i].kind === 1) {
            that.fields[i].property = JSON.parse(that.fields[i].property)
          }
        }
        that.cntFormulaType = response.data.type
        this.previewDialogVisible = true
      }).catch((error) => {
        console.error(error)
        this.$message.error("获取计算器数据失败");
      });
    },
    //时间处理
    dateFormat: function (row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format("YYYY-MM-DD  HH:mm:ss")
    },
    release: function (id) {
      this.$confirm('确定发布？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = new URLSearchParams();
        param.append("id", id)
        this.axios.post('/pmph/action/medicalCalculator/CalculatorToRelease', param)
          .then((response) => {
            this.getTableData()
            this.$emit("released")
          })
      })
    },
    releaseSelection: function () {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning("请选择知识");
        return;
      }
      this.$confirm('确定发布？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post('/pmph/action/medicalCalculator/SelectionCalculatorToRelease', this.multipleSelection.map(item => item.id))
          .then(() => {
            this.getTableData()
            this.$emit("released")
          });
      })
    },
    releaseAll: function () {
      this.$confirm('确定发布？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/pmph/action/medicalCalculator/releaseAll', {
          params: {
            currentPage: 0, // 第几页
            pageSize: 10, // 每页显示的数据个数
            updateTime: this.updateTime.toString(),
            type: this.type,
            version: this.version,
            editor: this.editor,
            auditor: this.auditor,
            name: this.name,
            platform: JSON.stringify(this.platform),
            status: "queryAll"
          }
        }).then((response) => {
          this.getTableData()
          this.$emit("released")
        });
      })
    },
    getTableData: function () {
      let url = ''
      if (this.radioStatus === 'unpublished') {
        url = '/pmph/action/medicalCalculator/selectCalculatorList'
      } else {
        url = '/pmph/action/medicalCalculator/selectReleasedCalculatorList'
      }
      this.axios.get(url, {
        params: {
          currentPage: this.currentPage,
          pageNum: this.pageSize,
          updateTime: this.updateTime.toString(),
          type: this.type,
          version: this.version,
          editor: this.editor,
          auditor: this.auditor,
          name: this.name,
          platform: JSON.stringify(this.platform),
          status: this.radioStatus,
          subject: JSON.stringify(this.subject),
          isRevised: this.isRevised
        }
      }).then((response) => {
        this.noData = response.data.totalNum <= 0;
        this.TableData = response.data.tableData;
        this.totalNum = response.data.totalNum;
        for (let i = 0; i < response.data.tableData.length; i++) {
          this.tableInnerData.push(response.data.tableData[i].medicalCalculatorFieldList);
        }
      }).catch((error) => {
        console.error(error);
        this.TableData = [];
        this.noData = true;
        this.$message.error("未能请求到数据");
      })
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.getTableData()
    },
    reject(id) {
      this.$confirm('此操作将使子任务状态退回到最后一步审核状态，是否确定这样做？', '请确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.$prompt('请输入驳回原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '驳回原因不能为空'
        }).then(({value}) => {
          this.axios.get("/pmph/action/task/cancelAudit", {
            params: {
              id: id,
              reason: value
            }
          }).then(() => {
            this.getTableData()
          })
        })
      })
    }
  },
  activated() {
    this.getTableData()
  },
  created() {
    if (this.showStatus === 'true') {
      this.radioStatus = 'published'
      this.exportEnable = 'none'
      this.reviseEnable = 'none'
      this.optionEnable = 'none'
      this.exportEnable = 'none'
      this.editEnable = 'none'
      this.checkAllEnable = 'none'
      this.releaseEnable = 'none'
    } else {
      this.radioStatus = 'unpublished'
    }
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 160;
    this.getTableData()
  }
}
</script>

<style scoped>

</style>
